package logic

import (
	"cloud-disk/core/define"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/core/models"
	"cloud-disk/core/utils"
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLogic {
	return &UserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLogic) User(req *types.LoginRequest) (resp *types.LoginResponse, err error) {
	var user models.User
	err = l.svcCtx.DbConn.Table("user_basic").Where("name=? AND password =?", req.Name, utils.Md5Encode(req.Password)).First(&user).Error
	if err != nil {
		fmt.Println(err)
		return nil, errors.New("用户密码错误")
	}
	token, err := utils.GenToken(user.ID, user.Identity, user.Name, define.TokenExpires)
	if err != nil {
		return nil, err
	}
	refreshToken, err := utils.GenToken(user.ID, user.Identity, user.Name, define.RefreshTokenExpires)
	if err != nil {
		return nil, err
	}
	resp = new(types.LoginResponse)
	resp.Token = token
	resp.RefreshToken = refreshToken
	return
}
